<template>
  <div class="supplier-container">
    <h1>供应商管理</h1>

    <!-- 查询供应商 -->
    <el-card class="search-card">
      <el-form :model="query" label-width="100px" inline>
        <el-form-item label="供应商名称">
          <el-input v-model="query.name" placeholder="请输入供应商名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchSuppliers">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 新增供应商 -->
    <div class="toolbar">
      <el-button type="primary" @click="openAddDialog">新增供应商</el-button>
    </div>

    <!-- 供应商表格 -->
    <el-table
        :data="pagedData"
        border
        style="width: 100%"
        v-loading="loading"
        element-loading-text="数据加载中..."
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="供应商名称" width="180" />
      <el-table-column prop="contactPerson" label="联系人" width="120" />
      <el-table-column prop="phone" label="联系电话" width="150" />
      <el-table-column prop="address" label="地址" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="confirmDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-if="tableData.length > 0"
        background
        layout="prev, pager, next, sizes, total"
        :current-page="page"
        :page-size="pageSize"
        :page-sizes="[5, 10, 20]"
        :total="tableData.length"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        style="margin-top: 20px; justify-content: center;"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="editForm.id ? '编辑供应商' : '新增供应商'"
        width="500px"
    >
      <el-form :model="editForm" label-width="100px" ref="supplierForm">
        <el-form-item label="供应商名称" required>
          <el-input v-model="editForm.name" placeholder="请输入供应商名称" />
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="editForm.contactPerson" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="editForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="editForm.address" placeholder="请输入地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import supplierApi from '../api/supplierapi.js'

// 数据
const tableData = ref([])
const loading = ref(false)
const page = ref(1)
const pageSize = ref(5)
const query = reactive({ name: '' })

// 分页数据
const pagedData = computed(() => {
  const start = (page.value - 1) * pageSize.value
  return tableData.value.slice(start, start + pageSize.value)
})

// 对话框
const dialogVisible = ref(false)
const editForm = reactive({ id: null, name: '', contactPerson: '', phone: '', address: '' })

// 加载数据
const loadSuppliers = async () => {
  loading.value = true
  try {
    const res = await supplierApi.list(query)
    if (res && res.code === 200) {
      tableData.value = Array.isArray(res.data) ? res.data : []
    } else {
      tableData.value = []
    }
    page.value = 1
  } catch (err) {
    console.error(err)
    tableData.value = []
  } finally {
    loading.value = false
  }
}

const searchSuppliers = () => loadSuppliers()
const resetSearch = () => { query.name = ''; loadSuppliers() }

// 分页
const handlePageChange = (newPage) => (page.value = newPage)
const handleSizeChange = (newSize) => { pageSize.value = newSize; page.value = 1 }

// 新增/编辑
const openAddDialog = () => {
  Object.assign(editForm, { id: null, name: '', contactPerson: '', phone: '', address: '' })
  dialogVisible.value = true
}
const openEditDialog = (supplier) => {
  Object.assign(editForm, supplier)
  dialogVisible.value = true
}
const submitEdit = async () => {
  if (!editForm.name) return ElMessage.warning('供应商名称不能为空')
  try {
    if (editForm.id) await supplierApi.edit(editForm)
    else await supplierApi.add(editForm)
    dialogVisible.value = false
    loadSuppliers()
    ElMessage.success('操作成功')
  } catch (err) {
    console.error(err)
    ElMessage.error('操作失败')
  }
}

// 删除
const confirmDelete = (id) => {
  ElMessageBox.confirm('确定要删除该供应商吗？', '删除确认', { type: 'warning' })
      .then(async () => {
        await supplierApi.del(id)
        ElMessage.success('删除成功')
        loadSuppliers()
      })
      .catch(() => ElMessage.info('已取消删除'))
}

onMounted(loadSuppliers)
</script>

<style scoped>
.supplier-container {
  padding: 20px;
}
.search-card {
  margin-bottom: 20px;
}
.toolbar {
  margin-bottom: 20px;
  text-align: right;
}
</style>